package com.example.blog.modules.article.repository;

import com.example.blog.modules.article.entity.Comment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Repository
public interface CommentRepository extends JpaRepository<Comment, Long> {
    Page<Comment> findByArticleIdAndParentIsNull(Long articleId, Pageable pageable);
    List<Comment> findByParentId(Long parentId);
    
    @Modifying
    @Query("UPDATE Comment c SET c.likeCount = c.likeCount + 1 WHERE c.id = ?1")
    void incrementLikeCount(Long id);
    
    @Modifying
    @Query("UPDATE Comment c SET c.likeCount = c.likeCount - 1 WHERE c.id = ?1 AND c.likeCount > 0")
    void decrementLikeCount(Long id);
    
    @Modifying
    @Query("UPDATE Comment c SET c.isApproved = true WHERE c.id = ?1")
    void approve(Long id);
    
    @Query("SELECT COUNT(c) FROM Comment c WHERE c.article.id = ?1 AND c.isApproved = true")
    long countByArticleIdAndApproved(Long articleId);

    /**
     * 统计未审核的评论数量
     */
    long countByIsApprovedFalse();

    /**
     * 统计已审核的评论数量
     */
    long countByIsApprovedTrue();

    /**
     * 统计指定时间之后创建的评论数量
     */
    long countByCreatedAtAfter(LocalDateTime dateTime);

    /**
     * 统计指定时间段内创建的评论数量
     */
    long countByCreatedAtBetween(LocalDateTime startDate, LocalDateTime endDate);

    /**
     * 获取每日新增评论数
     */
    @Query("SELECT DATE(c.createdAt) as date, COUNT(c) as count " +
           "FROM Comment c " +
           "WHERE c.createdAt BETWEEN :startDate AND :endDate " +
           "GROUP BY DATE(c.createdAt)")
    Map<String, Long> findDailyNewComments(@Param("startDate") LocalDateTime startDate, 
                                         @Param("endDate") LocalDateTime endDate);
} 